<template>
  <view class="form-page">
    <!-- <view class="normal-title">子表</view> -->
    <view class="main-table">
      <bxform ref="bxForm" :service="serviceName" :addType="addType" :pageType="type" :BxformType="type"
        :defaultCondition="defaultCondition" :fields="fields" @value-blur="valueChange" :childDatas="childDatas"
        :moreConfig="colsV2Data && colsV2Data.more_config ? colsV2Data.more_config : null">
      </bxform>
    </view>


    <!-- 子表 -->
    <view class="child-service-box" v-if="childService&&childService.length>0">
      <view class="child-service" v-for="(item,index) in childService" :key="index">
        <view class="handler-bar" @click="changeChildTab(index)" v-if="childIndex!==index&&childService.length>1">
          <view class="title">
            {{item.label||''}}
          </view>
          <view class="handler">
            <button class="cu-btn bg-white round"><text class="cuIcon-unfold"></text></button>
          </view>
        </view>
        <child-list :mainData="mainData" :disabled="disabled||detailDisabled" :mainTable="colsV2Data.main_table" :childService="item"
          v-if="item" v-show="childIndex===index" :appName="appName" ref="childList" @onButton="onChildButton"
          @change="childDataChange" @changeTab="changeChildTab(index)">
        </child-list>
      </view>
    </view>


    <view class="button-box" v-if="colsV2Data && isArray(fields) && fields.length > 0&&disabled!==true">
      <view v-for="(item, index) in buttons" :key="index" class="button">
        <button v-if="item.display !== false" @click="onButton(item)"
          class="cu-btn bg-blue round">{{ item.button_name }}</button>
      </view>
    </view>
  </view>
</template>

<script>
  import bxform from '@/components/bx-form/bx-form.vue';
  export default {
    components: {
      bxform
    },
    props: {},
    data() {
      return {
        appName: "",
        fields: [],
        colsV2Data: null,
        type: '',
        serviceName: '',
        condition: [],
        defaultCondition: [],
        params: {},
        addType: '',
        fieldsCond: [], //treeSelector类型字段的条件
        defaultVal: null,
        mainData: null,
        childIndex: 0,
        addV2: null,
        updateV2: null,
        detailV2: null,
        childDatas: {},
        disabled: false,
        detailDisabled:false
      };
    },
    computed: {
      formButton() {
        return this.colsV2Data?.formButton
      },
      childService: {
        get() {
          let result = []
          if (['update', 'add'].includes(this.type)) {
            result = this.operateChildService
          } else {
            result = this.detailChildService
          }
          if (Array.isArray(result)) {
            return result.map(item => {
              if (item?.foreign_key?.section_name) {
                item.label = item.foreign_key.section_name
              }
              if (item?.foreign_key?.more_config) {
                try {
                  item.foreign_key.moreConfig = JSON.parse(item.foreign_key.more_config)
                } catch (e) {

                }
              }
              return item
            }).filter((item, index) => {
              if (Array.isArray(this.mainData?._child_tables) && result.length === this.mainData
                ._child_tables.length) {
                if (this.mainData._child_tables[index] === 0) {
                  return false
                }
              }
              if (item.foreign_key?.moreConfig?.show_in_mobile === false) {
                return false
              }
              return true
            })
          }
          return result
        }
      },
      operateChildService() {
        return this.detailV2?.child_service.filter(item => {
          if (item.foreign_key?.foreign_key_type === '主子表') {
            // item.use_type = 'add'
            if (this.type === 'update') {
              item.use_type = 'updatechildlist'
            } else if (this.type === 'add') {
              item.use_type = 'addchildlist'
            }
            return true
          }
        })
      },
      detailChildService() {
        return this.detailV2?.child_service.filter(item => {
          // return item.foreign_key?.foreign_key_type === '字段引用'
          return item.foreign_key?.foreign_key_type !== '主子表'
        })
      },
      buttons: function() {
        let buttons = [];
        if (this.colsV2Data && this.colsV2Data._buttonInfo) {
          buttons = this.colsV2Data._buttonInfo;
        } else if (this.colsV2Data && this.colsV2Data._formButtons) {
          buttons = this.colsV2Data._formButtons;
        }
        buttons = buttons.filter(item => item.button_name !== '重置');
        let data = {};
        this.fields.forEach(item => {
          data[item['column']] = item['value'];
        });
        let fieldModel = data;
        buttons.forEach(btn => {
          if (btn.disp_exps) {
            // #ifdef H5
            btn['display'] = eval(btn.disp_exps);
            // #endif
          }
          if (btn.operate_params) {
            let fieldData = btn.operate_params['data'];
            if (fieldData && Array.isArray(fieldData) && fieldData.length > 0) {
              fieldData = fieldData[0];
              let newData = {};
              Object.keys(fieldData).forEach(data_item => {
                let item = fieldData[data_item];
                if (item.value_type && item.value_type === 'rowData') {
                  newData[data_item] = fieldModel[item.value_key];
                }
              });
              btn['requestData'] = newData;
              btn['requestCondition'] = this.condition;
            }
          }
        });
        return buttons;
      }
    },
    created() {
      const destApp = this.$route ? this.$route.query.destApp : '';
      if (destApp) {
        uni.setStorageSync('activeApp', destApp);
      }
    },
    onLoad(option) {
      if (option.disabled) {
        this.disabled = true
      }
      if(option.detailDisabled){
        this.detailDisabled = true
      }
      let destApp = option.destApp;
      if (destApp) {
        uni.setStorageSync('activeApp', destApp);
      } else {
        destApp = uni.getStorageSync('activeApp')
      }
      this.appName = destApp
      if (option.main_data) {
        try {
          this.mainData = JSON.parse(option.main_data)
        } catch (e) {
          //TODO handle the exception
        }
      }
      if (option.fieldsCond) {
        this.fieldsCond = JSON.parse(decodeURIComponent(option.fieldsCond));
      }
      if (option.addType) {
        this.addType = option.addType;
      }
      if (option.cond) {
        this.defaultCondition = JSON.parse(option.cond);
      }
      if (option.hasOwnProperty('params')) {
        try {
          if (typeof option.params === 'string' && (option.params.indexOf('%7B') || option.params.indexOf(
              '%3A')) !==
            -1) {
            this.params = JSON.parse(decodeURIComponent(option.params));
          } else {
            this.params = JSON.parse(option.params);
          }
        } catch (e) {
          //TODO handle the exception
        }
        debugger
        this.serviceName = this.params?.serviceName;
        this.type = this.params?.type;
        this.condition = this.params?.condition;
        this.defaultVal = this.params?.defaultVal;
        this.getFieldsV2();
      } else if (option.serviceName && option.type) {
        this.serviceName = option.serviceName;
        this.type = option.type;
        this.getFieldsV2();
      } else {
        uni.showToast({
          title: '加载错误',
          icon: 'none'
        });
      }
    },
    methods: {
      childDataChange(e) {
        if (e?.info?.constraint_name && e?.data) {
          this.$set(this.childDatas, e.info.constraint_name, e.data)
          // this.childDatas[e.info.constraint_name] = e.data
        }
      },
      changeChildTab(index) {
        if (index === this.childIndex && this.childService.length > 1) {
          this.childIndex = null
        } else {
          this.childIndex = index
        }
      },
      valueChange(e, fieldModel) {
        this.mainData = fieldModel
      },
      onChildButton(e) {
        debugger
      },
      async getDetailV2() {
        const app = this.appName || uni.getStorageSync('activeApp');
        let colVs = await this.getServiceV2(this.serviceName, 'detail', 'detail', app);

        this.detailV2 = colVs
      },
      toChildServiceList(e) {
        let data = this.deepClone(e);
        let formData = this.params.defaultVal;
        let condition = [{
          colName: e.foreign_key.column_name,
          ruleType: 'eq',
          value: formData[e.foreign_key.referenced_column_name]
        }];
        if (e.foreign_key && e.foreign_key.more_config && typeof e.foreign_key.more_config === 'string') {
          try {
            e.foreign_key.more_config = JSON.parse(e.foreign_key.more_config);
          } catch (e) {
            //TODO handle the exception
          }
        }
        if (e.foreign_key && e.foreign_key.more_config && formData[e.foreign_key.referenced_column_name]) {
          let moreConfig = e.foreign_key.more_config;
          if (e.foreign_key.more_config.targetType) {
            let targetType = e.foreign_key.more_config.targetType;
            if (targetType === 'list') {
              uni.navigateTo({
                url: '/pages/public/list/list?pageType=list&serviceName=' + e.service_name +
                  '&cond=' + JSON.stringify(condition)
              });
            } else if (targetType === 'detail') {
              if (e.childData && e.childData.data && e.childData.data.length > 0) {
                let params = {
                  type: 'update',
                  formDisabled: true,
                  condition: [{
                    colName: 'id',
                    ruleType: 'in',
                    value: e.childData.data[0].id
                  }],
                  serviceName: e.service_name
                  // "defaultVal": row
                };
                uni.navigateTo({
                  url: '/pages/public/formPage/formPage?params=' + JSON.stringify(params)
                });
              } else {
                uni.showModal({
                  title: '提示',
                  content: '暂无数据，是否添加数据',
                  success(res) {
                    if (res.confirm) {
                      let params = {
                        type: 'add',
                        serviceName: e.service_name.replace('_select', '_add')
                        // defaultVal:formData
                      };
                      // referenced_column_name //被引用的字段
                      // column //子表字段
                      console.log(e);
                      if (e.foreign_key && e.foreign_key.referenced_column_name && e
                        .foreign_key.column_name) {
                        params.defaultCondition = [{
                          colName: e.foreign_key.referenced_column_name,
                          ruleType: 'eq',
                          value: formData[e.foreign_key.column_name]
                        }];
                      }
                      uni.navigateTo({
                        url: '/pages/public/formPage/formPage?params=' + JSON
                          .stringify(params)
                      });
                    }
                  }
                });
              }
            }
          }
          if (moreConfig.app_list_column && typeof moreConfig.app_list_column == 'object' && moreConfig
            .app_list_column.title) {
            uni.navigateTo({
              url: '/pages/public/list/list?pageType=list&serviceName=' +
                e.service_name +
                '&cond=' +
                JSON.stringify(condition) +
                '&viewTemp=' +
                JSON.stringify(moreConfig.app_list_column)
            });
          }
        } else {
          uni.navigateTo({
            url: '/pages/public/list/list?pageType=list&serviceName=' + e.service_name + '&cond=' +
              JSON.stringify(condition) + '&showNavBack=' + true
          });
        }
      },
      toUpdatePages() {
        let params = {
          type: 'update',
          condition: this.params.condition,
          serviceName: this.params.serviceName.replace('_select', '_update'),
          defaultVal: this.params.defaultVal
        };
        uni.navigateTo({
          url: '/pages/public/formPage/formPage?params=' + JSON.stringify(params)
        });
      },
      async getDefaultVal() {
        
        if (this.type === 'detail' || this.type === 'update') {
          let app = uni.getStorageSync('activeApp');
          let serviceName = this.params?.service || this.params?.serviceName
          if (serviceName) {
            serviceName = serviceName.replace('_update', '_select')
          } else {
            return
          }
          let url = this.getServiceUrl(app, serviceName, 'select');
          let req = {
            serviceName: serviceName,
            colNames: ['*'],
            condition: this.params.condition || this.defaultCondition || this.condition,
            page: {
              pageNo: 1,
              rownumber: 10
            }
          };
          if (!req.condition) {
            return
          }
          if (this.colsV2Data?.vpage_no) {
            req['vpage_no'] = this.colsV2Data.vpage_no
          }
          let res = await this.$http.post(url, req);
          if (res.data.state === 'SUCCESS') {
            if (Array.isArray(res.data.data) && res.data.data.length > 0) {
              this.mainData = res.data.data[0];
              return res.data.data[0];
            }
          }
        }
      },
      getFieldsV2: async function() {
        let self = this
        let app = uni.getStorageSync('activeApp');
        let colVs = await this.getServiceV2(this.serviceName, this.type, this.type, app);
        let defaultVal = this.defaultVal;
        // colv = self.deepClone(colVs);

        this.colsV2Data = colVs;

        if (!colVs) {
          return
        }

        this[`${this.type}V2`] = colVs

        if (['update', 'add'].includes(this.type)) {
          this.getDetailV2()
        }

        if (colVs.more_config && typeof colVs.more_config === 'string') {
          try {
            colVs.more_config = JSON.parse(colVs.more_config)
          } catch (e) {
            //TODO handle the exception
          }
        }
        
        if (colVs.service_view_name) {
          uni.setNavigationBarTitle({
            title: colVs.service_view_name
          });
        }
        
        switch (this.type) {
          case 'update':
            if ((defaultVal && Object.keys(defaultVal).length === 0) || !defaultVal) {
              defaultVal = await this.getDefaultVal();
            }
            this.fields = this.setFieldsDefaultVal(colVs._fieldInfo, defaultVal || this.params
              .defaultVal || {});
            break;
          case 'add':
            this.fields = colVs._fieldInfo.map(field => {
              if (this.params?.defaultVal && Object.keys(this.params.defaultVal).length > 0) {
                Object.keys(this.params.defaultVal).forEach(key => {
                  if (key === field.column) {
                    field.value = this.params.defaultVal[key]
                  }
                })
              }
              if (this.defaultCondition && Array.isArray(this.defaultCondition) && colVs
                ._fieldInfo && Array.isArray(colVs._fieldInfo)) {
                this.defaultCondition.forEach(cond => {
                  colVs._fieldInfo.forEach(field => {
                    if (cond.colName === field.column) {
                      field['value'] = cond['value'];
                      // field['disabled'] = true;
                    }
                  });
                });
              }
              if (Array.isArray(this.fieldsCond) && this.fieldsCond.length > 0) {
                this.fieldsCond.forEach(item => {
                  if (item.column === field.column && field.option_list_v2 && Array
                    .isArray(field.option_list_v2.conditions) && Array.isArray(item
                      .condition)) {
                    field.option_list_v2.conditions = field.option_list_v2
                      .conditions.concat(item.condition);
                  }
                });
              }
              return field;
            });
            break;
          case 'detail':
            defaultVal = await this.getDefaultVal();
            this.fields = this.setFieldsDefaultVal(colVs._fieldInfo, defaultVal ? defaultVal : this.params
              .defaultVal);
            break;
          default:
            break;
        }
        this.defaultVal = defaultVal || {}
      },
      async onButton(e) {
        let filedModal = this.$refs.bxForm.getFieldModel();
        console.log(filedModal)
        if (filedModal === false) {
          return
        }
        filedModal = this.deepClone(filedModal)
        let defaultVal = this.deepClone(this.defaultVal)

        for (let key in filedModal) {
          if (((!filedModal[key] && !defaultVal[key]) || filedModal[key] === defaultVal[key]) && this.type != "add") {
            delete filedModal[key];
            // 判断如果值相等得就话就删除
          } else if (!filedModal[key] && filedModal[key] !== 0) {
            filedModal[key] = null
            if (this.type == "add") {
              delete filedModal[key]
            }
          }
        }
        let req = []
        switch (e.button_type) {
          case 'edit':
            if (e.page_type === '详情' && this.type === 'detail') {
              this.type = 'update';
              await this.getFieldsV2();
            } else {
              if (filedModal) {
                let data = this.deepClone(filedModal);
                data.child_data_list = []
                this.childService.forEach((item, index) => {
                  let childDataList = this.$refs.childList[index].getChildDataList()
                  data.child_data_list = [...data.child_data_list, ...childDataList]
                })
                if (data._children) {
                  delete data._children
                }
                req = [{
                  serviceName: e.service_name,
                  data: [data],
                  condition: this.condition || this.defaultCondition
                }];
                if (!req[0].condition) {
                  uni.showToast({
                    title: '系统错误,请刷新后重试',
                    icon: 'none'
                  })
                  return
                }
                let app = uni.getStorageSync('activeApp');
                let url = this.getServiceUrl(app, e.service_name, 'add');
                let res = await this.onRequest('update', e.service_name, req);
                console.log('res:' + e.service_name, res);
                if (res.data.state === 'SUCCESS') {
                  let resData = this.getResData(res.data.response);
                  console.log('resData', resData);
                  this.type = 'detail';
                  await this.getFieldsV2();
                  uni.showModal({
                    title: '提示',
                    content: res.data.resultMessage,
                    showCancel: false,
                    success(res) {
                      if (res.confirm) {
                        uni.navigateBack({
                          delta: 1
                        })
                      }
                    }
                  })
                } else {
                  uni.showToast({
                    title: res.data.resultMessage,
                    mask: false,
                    icon: 'none'
                  });
                }
              }
            }
            break;
          case 'submit':
            if (filedModal) {
              filedModal = this.deepClone(filedModal)
              let data = this.deepClone(filedModal);
              data.child_data_list = []
              this.childService.forEach((item, index) => {
                let childDataList = this.$refs.childList[index].getChildDataList()
                data.child_data_list = [...data.child_data_list, ...childDataList]
              })
              if (data._children) {
                delete data._children
              }
              if (e.service_name === 'srvstore_health_body_exam_add') {
                data.health_soure = '店内设备'
                if(data.physical_result){
                  data. max_tz_name = data.physical_result
                }
              }
              if (e.service_name == 'srvstore_quality_measurement_add') {
                // 体制测量
                let arr = [{
                    name: '气虚质',
                    score: Number(data.score_qix_qdc)
                  },
                  {
                    name: '气郁质',
                    score: Number(data.score_qiy_qsc)
                  },
                  {
                    name: '湿热质',
                    score: Number(data.score_shir_dhc)
                  },
                  {
                    name: '痰湿质',
                    score: Number(data.score_tans_pdc)
                  },
                  {
                    name: '特禀质',
                    score: Number(data.score_teb_isc)
                  },
                  {
                    name: '血虚质',
                    score: Number(data.score_xuexu)
                  },
                  {
                    name: '血瘀质',
                    score: Number(data.score_xuey_bsc)
                  },
                  {
                    name: '阳虚质',
                    score: Number(data.score_yangx_yadc)
                  }
                ]
                let measurement_result = arr.reduce((res, cur) => {
                  if (res.score && cur.score < res.score) {
                    return res
                  } else {
                    return cur
                  }
                }, {})
                data.measurement_result = measurement_result?.name
              }
              req = [{
                serviceName: e.service_name,
                data: [data]
              }];
              let app = uni.getStorageSync('activeApp');
              let url = this.getServiceUrl(app, e.service_name, 'add');
              console.log(url, e);
              let res = await this.$http.post(url, req);
              console.log(url, res.data);
              if (res.data.state === 'SUCCESS') {
                if (e.service_name === 'srvstore_health_body_exam_add'&&data?.health_type=='体质') {
                  // 跳转到体质评估问卷页面
                  console.log(res.data)
                  let id = res?.data?.response?.[0]?.response?.effect_data?.[0]?.id
                  
                  if(id){
                    uni.redirectTo({
                      url:`/pages/specific/quest/quest?id=${id}`
                    })
                    return
                  }
                }
                uni.showModal({
                  title: '提示',
                  content: '添加成功',
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      uni.navigateBack();
                    }
                  }
                });
              } else {
                uni.showToast({
                  title: res.data.resultMessage,
                  mask: false,
                  icon: 'none'
                });
              }
            }
            break;
          case 'reset':
            this.$refs.bxForm.onReset().then(res => {
              if (res) {
                uni.showToast({
                  title: '已重置'
                });
              } else {
                uni.showToast({
                  title: '无效操作'
                });
              }
            });
            break;
          case 'customize':
            if (e.application && e.operate_service) {
              const url = this.getServiceUrl(e.application, e.operate_service, 'operate');
              const req = [{
                data: [e.requestData],
                serviceName: e.operate_service,
                srvApp: e.application
              }];
              let res = await this.$http.post(url, req);
              if (res.data.state === 'SUCCESS') {
                uni.showModal({
                  title: '提示',
                  content: e.tip_msg ? e.tip_msg : res.data.resultMessage,
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      uni.navigateBack();
                    }
                  }
                });
              } else {
                uni.showToast({
                  title: res.data.resultMessage,
                  mask: false,
                  icon: 'none'
                });
              }
            }
            break;
          default:
            uni.showToast({
              title: e.button_name
            });
            break;
        }
      }
    }
  };
</script>

<style lang="scss">
  .form-page {
    // min-height: 100vh;
    // background-color: #fff;
    margin: 20rpx;
    height: auto;

    .normal-title {
      margin-bottom: 20rpx;
      margin-left: 10rpx;
      padding: 0;
      display: inline-block;
      position: relative;
      width: 100%;
      text-indent: 30rpx;
      font-weight: bold;
      font-size: 32rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 10%;
        height: 80%;
        width: 5px;
        background-color: #0081ff;
        border-radius: 5rpx;
      }
    }

    .main-table {
      margin-top: 28upx;

      .normal-title {
        margin-left: 20rpx;
      }
    }

    .child-service-box {
      display: flex;
      flex-wrap: wrap;

      .child-service {
        width: 100%;
        background-color: #fff;
        margin: 20rpx 0 0;
        padding: 20rpx;
      }

      .handler-bar {
        display: flex;
        padding: 0 20rpx;
        width: 100%;

        .title {
          flex: 1;
          font-weight: 600;
        }

        .handler {
          display: flex;
          flex-wrap: wrap;
          max-width: 50%;

          .cu-btn {
            margin-left: 10rpx;
          }
        }

      }

      .child-service-item {
        min-height: 100rpx;
        width: calc(33% - 6rpx);
        display: flex;
        justify-content: center;
        align-items: center;
        transform: translate(2px, 2px);
        background-color: #409eff;
        color: #fff;
        transition: 0.2s all ease-in-out;
        border-radius: 10rpx;
        margin-right: 10rpx;
        margin-bottom: 20rpx;

        &:nth-child(3n + 1) {
          margin-right: 0;
        }

        &:active {
          transform: translate(2px, 2px);
          color: #409eff;
          background: #ecf5ff;
          box-shadow: 0px 0px 4px #ecf5ff, 0 0 6px #b3d8ff;
        }

        .child-service-title {
          // color: #0081ff;
          letter-spacing: 2px;
          font-weight: bold;
        }
      }
    }
  }

  .button-box {
    display: flex;
    justify-content: space-around;
    align-items: center;
    min-height: 200rpx;
    // background-color: #fff;
    flex-wrap: wrap;

    .button {
      width: 60%;

      .cu-btn {
        width: 100%;
      }
    }
  }
</style>
